package com.sinoyd.itszyw.Activity;

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.sinoyd.itszyw.Dialog.LoadingDialog;
import com.sinoyd.itszyw.Dialog.SelectDialog;
import com.sinoyd.itszyw.Model.IssueInfo;
import com.sinoyd.itszyw.Model.MaintainTaskInfo;
import com.sinoyd.itszyw.Model.RepairsDepInfo;
import com.sinoyd.itszyw.Model.RepairsInfo;
import com.sinoyd.itszyw.Model.TaskTypeInfo;
import com.sinoyd.itszyw.R;
import com.sinoyd.itszyw.Util.DateUtils;
import com.sinoyd.itszyw.zxing.android.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.sinoyd.itszyw.MyApplication.createMaintainTask;
import static com.sinoyd.itszyw.MyApplication.db;
import static com.sinoyd.itszyw.MyApplication.imageListUrls;
import static com.sinoyd.itszyw.MyApplication.logRrowGuid;
import static com.sinoyd.itszyw.MyApplication.loginId;
import static com.sinoyd.itszyw.MyApplication.loginName;
import static com.sinoyd.itszyw.Util.ImageUrlUtils.getImageStr;
import static com.sinoyd.itszyw.Util.ImageUrlUtils.getPicNameFromPath;

/**
 * @createBy : Sinoyd 大饼洲
 * @description :
 * @projectName : ITYW
 * @creationDate: 2017-04-07 17:26
 */
@ContentView(R.layout.activity_task_add)

public class MaintainTaskAddActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, SelectDialog.SelectTaskTypeListener, SelectDialog.SelectTaskIssuerListener {

    @ViewInject(R.id.task_name)
    private EditText task_name;
    @ViewInject(R.id.task_type_name)
    private TextView task_type_name;
    @ViewInject(R.id.linear_hardware)
    private LinearLayout linear_hardware;
    @ViewInject(R.id.hardware_name)
    private TextView hardware_name;
    @ViewInject(R.id.task_issuer)
    private TextView task_issuer;
    @ViewInject(R.id.issue_date)
    private TextView issue_date;
    @ViewInject(R.id.task_handler)
    private TextView task_handler;
    @ViewInject(R.id.start_date)
    private TextView start_date;
    @ViewInject(R.id.finish_date)
    private TextView finish_date;
    @ViewInject(R.id.task_repairs_dep)
    private TextView task_repairs_dep;
    @ViewInject(R.id.task_repairs)
    private EditText task_repairs;
    @ViewInject(R.id.task_specification)
    private TextView task_specification;
    @ViewInject(R.id.resolved)
    private RadioButton resolved;
    @ViewInject(R.id.unsolved)
    private RadioButton unsolved;
    @ViewInject(R.id.solve_group)
    private RadioGroup solve_group;
    @ViewInject(R.id.task_description)
    private TextView task_description;
    @ViewInject(R.id.linear_operation)
    private LinearLayout linear_operation;


    @ViewInject(R.id.txt_title)
    private TextView txt_title;
    @ViewInject(R.id.linear_back)
    private LinearLayout linear_back;


    private LoadingDialog loadingDialog;

    private final int CODE_FOR_WRITE_PERMISSION = 1;

    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 1;
    private static final String DECODED_CONTENT_KEY = "result";
    private static final int REQUEST_CODE_SCAN = 0x0000;
    private static final int REQUEST_CODE_REPAIRS = 1000;
    private static final int REQUEST_CODE_REPAIRS_DEP = 2000;

    private static final int REQUEST_IMAGES_LIST = 1001;
    private static int RRQUEST_POST_CREATEMAINTAIN = 111;

    private String issueDateStr = "";
    private String issueTimeStr = "";

    private String startDateStr = "";
    private String startTimeStr = "";

    private String endDateStr = "";
    private String endTimeStr = "";

    private Calendar calendarIssue;
    private Calendar calendarStart;
    private Calendar calendarFinish;

    private MaintainTaskInfo taskInfo;
    private String strSolved = "true";
    private String strHardwareId = "";

    private List typeList = new ArrayList();
    private List issueList = new ArrayList();
    private String issueId = "";
    private String repairsId = "";
    private String repairsDepId = "";
    private Boolean update;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

    }

    private void initView() {
        taskInfo = new MaintainTaskInfo();
        linear_back.setVisibility(View.VISIBLE);
        txt_title.setText(this.getResources().getString(R.string.task_add));
        loadingDialog = new LoadingDialog(this, R.style.dialog_translucent_notitle);
        Date dateNow = new Date();
//        String second = String.format("%tT", dateNow);
        issue_date.setText(String.format("%tF %tT", dateNow, dateNow));

        task_issuer.setText(loginName);
        task_handler.setText(loginName);
//        task_repairs.setText(loginName);
        issueId = logRrowGuid;
//        repairsId = logRrowGuid;
        resolved.setChecked(true);
        solve_group.setOnCheckedChangeListener(this);
        imageListUrls.clear();
//        task_name.setText(taskInfo.name);
//        task_type_name.setText(taskInfo.typeName);
//        hardware_name.setText(taskInfo.hardware);
//        task_issuer.setText(taskInfo.issuer);
//
//        task_specification.setText(taskInfo.specification);
//        task_description.setText(taskInfo.description);
//        task_issuer.setText(taskInfo.issuer);
//        finish_date.setText(taskInfo.finishDate);
//        task_specification.setText(taskInfo.specification);
//
//        solve_group.setOnCheckedChangeListener(this);
//        if (taskInfo.sloved.equals("true")) {
//            resolved.setChecked(true);
//        } else {
//            unsolved.setChecked(true);
//        }
//        strSolved = taskInfo.sloved;
//        strHardwareId = taskInfo.hardwareId;
//        linear_hardware.setVisibility(taskInfo.typeName.equals("硬件") ? View.VISIBLE : View.GONE);
//        linear_operation.setVisibility(taskInfo.state.equals("2") ? View.GONE : View.VISIBLE);
        calendarIssue = Calendar.getInstance();
        calendarStart = Calendar.getInstance();
        calendarFinish = Calendar.getInstance();

        try {
            typeList = db.findAll(TaskTypeInfo.class);
            issueList = db.findAll(IssueInfo.class);
        } catch (DbException e) {
            e.printStackTrace();
        }

        //默认信息中心
        task_repairs_dep.setText("信息中心");
        repairsDepId = "ad184f56-06f4-4727-8620-77882488d68a";

    }

    @Override
    public void httpOnSuccess(String responseStr, int requestCode) {
        if (requestCode == RRQUEST_POST_CREATEMAINTAIN) {
            try {
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {

                    taskInfo.state = update ? "2" : "1";
                    taskInfo.issuer = task_issuer.getText().toString();
                    taskInfo.handler = loginName;
                    taskInfo.issuerId = issueId;
                    taskInfo.repairsDepId = repairsDepId;
                    taskInfo.repairsId = task_repairs.getText().toString();
                    taskInfo.repairs = task_repairs.getText().toString();
                    taskInfo.taskId = "";
                    taskInfo.name = task_name.getText().toString();
                    taskInfo.issueDate = issue_date.getText().toString();
                    taskInfo.startDate = start_date.getText().toString();
                    taskInfo.finishDate = finish_date.getText().toString();
                    taskInfo.hardwareId = strHardwareId;
                    taskInfo.hardwareName = hardware_name.getText().toString();
                    taskInfo.sloved = strSolved;
                    taskInfo.typeName = task_type_name.getText().toString();
                    taskInfo.description = task_description.getText().toString();
                    taskInfo.specification = task_specification.getText().toString();
                    if (imageListUrls.size() > 1) {
                        JSONArray imagesArray = new JSONArray(imageListUrls);
                        taskInfo.images = imagesArray.toString();
//                        taskInfo.images = imageListUrls;
                        imageListUrls.clear();
                    }
                    try {
                        db.saveOrUpdate(taskInfo);
                        showToast("操作成功");
                        finish();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                } else {
                    showToast("上传字段or格式错误");
                    finish();
                }
                loadingDialog.dismiss();

            } catch (JSONException e) {
                e.printStackTrace();
                showToast(e.getMessage());
            }

        }
    }


    @Event({R.id.linear_back, R.id.scan, R.id.take_photo, R.id.linear_finish, R.id.linear_start, R.id.linear_issue_date, R.id.linear_type, R.id.linear_issuer, R.id.linear_repairs_dep, R.id.uploading, R.id.save})
    private void getOnclick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.take_photo:

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //如果没有授权，则请求授权
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_FOR_WRITE_PERMISSION);
                } else {
                    //有授权，直接询问
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        //如果没有授权，则请求授权
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                    } else {
                        //有授权，直接开启摄像头
                        Intent takePhotoIntent = new Intent(this, MaintainTaskPhotosActivity.class);
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable("taskInfo",getIntent().getSerializableExtra("task"));
//                        takePhotoIntent.putExtras(bundle);
                        takePhotoIntent.putExtra("taskInfo", getIntent().getSerializableExtra("task"));
                        startActivityForResult(takePhotoIntent, REQUEST_IMAGES_LIST);
                    }

                }

                break;
            case R.id.scan:

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //如果没有授权，则请求授权
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                } else {
                    //有授权，直接开启摄像头
                    Intent intent = new Intent(MaintainTaskAddActivity.this,
                            CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);

                }

                break;
            case R.id.linear_issue_date:
                showIssueDatePickDlg();
                break;
            case R.id.linear_start:
                if (issue_date.getText().toString().equals("")) {
                    showToast("先安排任务下发时间!");
                } else {
                    showStartDatePickDlg();
                }
                break;

            case R.id.linear_finish:
                if (start_date.getText().toString().equals("")) {
                    showToast("先安排任务开始时间!");
                } else {
                    showFinishDatePickDlg();
                }

                break;
            case R.id.linear_type:
                List typeLists = new ArrayList<>();
                for (int i = 0; i < typeList.size(); i++) {
                    TaskTypeInfo taskTypeInfo = (TaskTypeInfo) typeList.get(i);
                    typeLists.add(taskTypeInfo.typeName);
                }
                SelectDialog typeDialog = new SelectDialog(MaintainTaskAddActivity.this, typeLists, R.style.dialog_no_dimenabled);
                typeDialog.setSelectTaskTypeListener(this);
                typeDialog.show();
                break;
            case R.id.linear_repairs_dep:
                Intent intentIssuer = new Intent(MaintainTaskAddActivity.this, MaintainTaskRepairsDepActivity.class);
                startActivityForResult(intentIssuer, REQUEST_CODE_REPAIRS_DEP);
                break;
            case R.id.linear_issuer:

                SelectDialog handlerDialog = new SelectDialog(MaintainTaskAddActivity.this, issueList, R.style.dialog_no_dimenabled);
                handlerDialog.setSelectTaskIssuerListener(this);
                handlerDialog.show();
                break;

            case R.id.uploading:
                update = true;
                String taskType = "";
                if (task_name.getText().toString().equals("")) {
                    showToast("请填写任务名称");
                    break;
                }
                if (task_type_name.getText().toString().equals("")) {
                    showToast("请填选择任务类型");
                    break;
                }
                if (issue_date.getText().toString().equals("")) {
                    showToast("下发时间项为空");
                    break;
                }
                if (start_date.getText().toString().equals("")) {
                    showToast("开始时间项为空");
                    break;
                }
                if (finish_date.getText().toString().equals("")) {
                    showToast("完成时间项为空");
                    break;
                }

                if (task_specification.getText().toString().equals("")) {
                    showToast("任务说明为空");
                    break;
                }
                try {
                    TaskTypeInfo taskTypeInfo = (TaskTypeInfo) db.selector(TaskTypeInfo.class)
                            .where("type_name", "=", task_type_name.getText().toString())
                            .findFirst();
                    taskType = taskTypeInfo.typeId;
                } catch (DbException e) {
                    e.printStackTrace();
                }

//格式化初次获取的默认完成时间
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                //得到指定模范的时间
//                Date endDate = null;
//                try {
//                    endDate = sdf.parse(finish_date.getText().toString());
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//
//                String finishDate = DateUtils.getDateStrNumber(sdf.format(endDate));
                String issueTime = DateUtils.getDateStrNumber(issue_date.getText().toString());
                String startTime = DateUtils.getDateStrNumber(start_date.getText().toString());
                String endTime = DateUtils.getDateStrNumber(finish_date.getText().toString());
                loadingDialog.show();

                RequestParams params = new RequestParams(createMaintainTask);
                params.addBodyParameter("UserId", loginId);
                params.addBodyParameter("RegistDepGuid", repairsDepId);
                params.addBodyParameter("RegistManGuid", task_repairs.getText().toString());
                params.addBodyParameter("ReleaseManGuid", issueId);
                params.addBodyParameter("ReleaseTime", issueTime);
                params.addBodyParameter("StartTime", startTime);
                params.addBodyParameter("EndTime", endTime);
                params.addBodyParameter("TaskName", task_name.getText().toString().toLowerCase());
                params.addBodyParameter("TaskVariety", taskType);
                params.addBodyParameter("HardWareNum", strHardwareId);
                params.addBodyParameter("IsProcess", strSolved);
                params.addBodyParameter("Content", task_specification.getText().toString());
                params.addBodyParameter("ProcessContent", task_description.getText().toString());
                params.addBodyParameter("FileNames", getPicNameFromPath(imageListUrls));
                params.addBodyParameter("ImageStrs", getImageStr(imageListUrls));
                params.addBodyParameter("Type", "2");
                params.addBodyParameter("validation", "sinoyd123!@#");

                try {
                    sendHttpRequest(params, HttpMethod.POST, RRQUEST_POST_CREATEMAINTAIN);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case R.id.save:
                update = false;
                String saveTaskType = "";
                if (task_name.getText().toString().equals("")) {
                    showToast("请填写任务名称");
                    break;
                }
                if (task_type_name.getText().toString().equals("")) {
                    showToast("请填选择任务类型");
                    break;
                }
                if (issue_date.getText().toString().equals("")) {
                    showToast("下发时间项为空");
                    break;
                }
                if (task_specification.getText().toString().equals("")) {
                    showToast("任务说明为空");
                    break;
                }
                try {
                    TaskTypeInfo taskTypeInfo = (TaskTypeInfo) db.selector(TaskTypeInfo.class)
                            .where("type_name", "=", task_type_name.getText().toString())
                            .findFirst();
                    saveTaskType = taskTypeInfo.typeId;
                } catch (DbException e) {
                    e.printStackTrace();
                }

                String saveIssueTime = DateUtils.getDateStrNumber(issue_date.getText().toString());
                String saveStartTime = DateUtils.getDateStrNumber(start_date.getText().toString());
                String saveEndTime = DateUtils.getDateStrNumber(finish_date.getText().toString());
                loadingDialog.show();
                RequestParams saveParams = new RequestParams(createMaintainTask);
                saveParams.addBodyParameter("UserId", loginId);
                saveParams.addBodyParameter("RegistDepGuid", repairsDepId);
                saveParams.addBodyParameter("RegistManGuid", task_repairs.getText().toString());
                saveParams.addBodyParameter("ReleaseManGuid", issueId);
                saveParams.addBodyParameter("ReleaseTime", saveIssueTime);
                saveParams.addBodyParameter("StartTime", saveStartTime);
                saveParams.addBodyParameter("EndTime", saveEndTime);
                saveParams.addBodyParameter("TaskName", task_name.getText().toString());
                saveParams.addBodyParameter("TaskVariety", saveTaskType);
                saveParams.addBodyParameter("HardWareNum", strHardwareId);
                saveParams.addBodyParameter("IsProcess", strSolved);
                saveParams.addBodyParameter("Content", task_specification.getText().toString());
                saveParams.addBodyParameter("ProcessContent", task_description.getText().toString());
                saveParams.addBodyParameter("FileNames", "");
                saveParams.addBodyParameter("ImageStrs", "");
                saveParams.addBodyParameter("Type", "1");
                saveParams.addBodyParameter("validation", "sinoyd123!@#");
                try {
                    sendHttpRequest(saveParams, HttpMethod.POST, RRQUEST_POST_CREATEMAINTAIN);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 比较 下发时间  与 开始日期
     */
    protected void showIssueDatePickDlg() {

        final DatePickerDialog datePickerDialog = new DatePickerDialog(this, null, calendarIssue.get(calendarIssue.YEAR), calendarIssue.get(calendarIssue.MONTH), calendarIssue.get(calendarIssue.DAY_OF_MONTH));

        //手动设置按钮
        datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "完成", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //通过mDialog.getDatePicker()获得dialog上的DatePicker组件，然后可以获取日期信息
                DatePicker datePicker = datePickerDialog.getDatePicker();
                int year = datePicker.getYear();
                int month = datePicker.getMonth();
                int day = datePicker.getDayOfMonth();
                issueDateStr = String.format("%d-%02d-%02d", year, month + 1, day);

                SimpleDateFormat format = new SimpleDateFormat(
                        "yyyy-MM-dd");
                Date dateStart = null;
                try {
                    dateStart = format.parse(issueDateStr);// 完成日期
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                calendarIssue.setTime(dateStart);// 设置结束日历时间

//                compareDateSet();
                showIssueTimePickDlg();
            }
        });

        //取消按钮，如果不需要直接不设置即可
        datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.out.println("BUTTON_NEGATIVE~~");
            }
        });

//        datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
        datePickerDialog.show();


    }

    protected void showIssueTimePickDlg() {


        calendarIssue.setTimeInMillis(System.currentTimeMillis());


        TimePickerDialog timePickerDialog = new TimePickerDialog(MaintainTaskAddActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {

                Date dateNow = new Date();
                String second = String.format("%tT", dateNow);

                issueTimeStr = String.format("%02d:%02d:%s", i, i1, second.substring(second.length() - 2, second.length()));
//                calendar.setTimeInMillis(System.currentTimeMillis());
//                calendar.set(Calendar.HOUR_OF_DAY, i);
//                calendar.set(Calendar.MINUTE, i1);
//                calendar.set(Calendar.SECOND, 0); // 设为 0
//                calendar.set(Calendar.MILLISECOND, 0); // 设为 0
                issue_date.setText(issueDateStr + " " + issueTimeStr);
                start_date.setText("");
                finish_date.setText("");
            }
        }, calendarIssue.get(calendarIssue.HOUR_OF_DAY), calendarIssue.get(calendarIssue.MINUTE), true);
        timePickerDialog.show();
    }


    /**
     * 比较 开始时间  与 下发日期
     */
    protected void showStartDatePickDlg() {

        final DatePickerDialog datePickerDialog = new DatePickerDialog(this, null, calendarStart.get(calendarStart.YEAR), calendarStart.get(calendarStart.MONTH), calendarStart.get(calendarStart.DAY_OF_MONTH));

        //手动设置按钮
        datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "完成", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //通过mDialog.getDatePicker()获得dialog上的DatePicker组件，然后可以获取日期信息
                DatePicker datePicker = datePickerDialog.getDatePicker();
                int year = datePicker.getYear();
                int month = datePicker.getMonth();
                int day = datePicker.getDayOfMonth();
                startDateStr = String.format("%d-%02d-%02d", year, month + 1, day);

                SimpleDateFormat format = new SimpleDateFormat(
                        "yyyy-MM-dd");
                Date dateStart = null;
                try {
                    dateStart = format.parse(startDateStr);// 完成日期
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                calendarStart.setTime(dateStart);// 设置结束日历时间

//                compareDateSet();
                showStartTimePickDlg();
            }
        });

        //取消按钮，如果不需要直接不设置即可
        datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.out.println("BUTTON_NEGATIVE~~");
            }
        });

//        datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
        datePickerDialog.show();


    }

    protected void showStartTimePickDlg() {


        calendarStart.setTimeInMillis(System.currentTimeMillis());


        TimePickerDialog timePickerDialog = new TimePickerDialog(MaintainTaskAddActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {

                Date dateNow = new Date();
                String second = String.format("%tT", dateNow);

                startTimeStr = String.format("%02d:%02d:%s", i, i1, second.substring(second.length() - 2, second.length()));
//                calendar.setTimeInMillis(System.currentTimeMillis());
//                calendar.set(Calendar.HOUR_OF_DAY, i);
//                calendar.set(Calendar.MINUTE, i1);
//                calendar.set(Calendar.SECOND, 0); // 设为 0
//                calendar.set(Calendar.MILLISECOND, 0); // 设为 0
                compareDateSetStart();
            }
        }, calendarStart.get(calendarStart.HOUR_OF_DAY), calendarStart.get(calendarStart.MINUTE), true);
        timePickerDialog.show();
    }

    private void compareDateSetStart() {


        //格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //得到指定模范的时间
        Date issueDate = null;
        Date startDate = null;
        try {
            issueDate = sdf.parse(issue_date.getText().toString());
            startDate = sdf.parse(startDateStr + " " + startTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }


//            //比较
//            if(Math.abs(((d1.getTime() - d2.getTime())/(24*3600*1000))) >=3) {
//                System.out.println("大于三天");
//            }else{
//                System.out.println("小于三天");
//            }

        //比较
        if ((startDate.getTime() - issueDate.getTime()) < 0) {
            showToast("开始时间不能早于下发时间");
        } else {
            start_date.setText(startDateStr + " " + startTimeStr);
            finish_date.setText("");
        }

    }

    /**
     * 比较 开始时间  与 完成日期
     */
    protected void showFinishDatePickDlg() {

        final DatePickerDialog datePickerDialog = new DatePickerDialog(this, null, calendarFinish.get(calendarFinish.YEAR), calendarFinish.get(calendarFinish.MONTH), calendarFinish.get(calendarFinish.DAY_OF_MONTH));

        //手动设置按钮
        datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "完成", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //通过mDialog.getDatePicker()获得dialog上的DatePicker组件，然后可以获取日期信息
                DatePicker datePicker = datePickerDialog.getDatePicker();
                int year = datePicker.getYear();
                int month = datePicker.getMonth();
                int day = datePicker.getDayOfMonth();
                endDateStr = String.format("%d-%02d-%02d", year, month + 1, day);

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date dateEnd = null;
                try {
                    dateEnd = format.parse(endDateStr);// 完成日期
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                calendarFinish.setTime(dateEnd);// 设置结束日历时间

//                compareDateSet();
                showFinishTimePickDlg();
            }
        });

        //取消按钮，如果不需要直接不设置即可
        datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.out.println("BUTTON_NEGATIVE~~");
            }
        });

//        datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
        datePickerDialog.show();


    }

    protected void showFinishTimePickDlg() {


        calendarFinish.setTimeInMillis(System.currentTimeMillis());


        TimePickerDialog timePickerDialog = new TimePickerDialog(MaintainTaskAddActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {

                Date dateNow = new Date();
                String second = String.format("%tT", dateNow);

                endTimeStr = String.format("%02d:%02d:%s", i, i1, second.substring(second.length() - 2, second.length()));
//                calendar.setTimeInMillis(System.currentTimeMillis());
//                calendar.set(Calendar.HOUR_OF_DAY, i);
//                calendar.set(Calendar.MINUTE, i1);
//                calendar.set(Calendar.SECOND, 0); // 设为 0
//                calendar.set(Calendar.MILLISECOND, 0); // 设为 0
                compareDateSetFinish();
            }
        }, calendarFinish.get(calendarFinish.HOUR_OF_DAY), calendarFinish.get(calendarFinish.MINUTE), true);
        timePickerDialog.show();
    }

    private void compareDateSetFinish() {


        //格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //得到指定模范的时间
        Date dateStart = null;
        Date endDate = null;
        try {
            dateStart = sdf.parse(start_date.getText().toString());
            endDate = sdf.parse(endDateStr + " " + endTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }


//            //比较
//            if(Math.abs(((d1.getTime() - d2.getTime())/(24*3600*1000))) >=3) {
//                System.out.println("大于三天");
//            }else{
//                System.out.println("小于三天");
//            }

        //比较
        if ((endDate.getTime() - dateStart.getTime()) < 0) {
            showToast("完成时间不能早于开始时间");
        } else {
            finish_date.setText(endDateStr + " " + endTimeStr);
        }

    }


    /**
     * 动态开启 相机权限、针对android SDK 23以上
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //判断请求码
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_CAMERA) {
            //grantResults授权结果
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Intent intent = new Intent(MaintainTaskAddActivity.this,
                        CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
                //成功，开启摄像头
            } else {
                //授权失败
                Toast.makeText(MaintainTaskAddActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        if (requestCode == CODE_FOR_WRITE_PERMISSION) {
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //用户同意使用write

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //如果没有授权，则请求授权
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                } else {
                    //有授权，直接开启摄像头
                    Intent takePhotoIntent = new Intent(this, MaintainTaskPhotosActivity.class);
                    startActivityForResult(takePhotoIntent, REQUEST_IMAGES_LIST);
                }

            } else {
                //用户不同意，自行处理即可
                //授权失败
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    /**
     * 二维码扫描返回
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                try {
                    JSONObject object = new JSONObject(content);
                    if (object.getString("AssetName") != null) {
                        hardware_name.setText(object.getString("AssetName"));
                        strHardwareId = object.getString("FixedNumber");
                        showToast("扫描成功");
                    } else {
                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }


//                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);

            }
        }

        if (requestCode == REQUEST_IMAGES_LIST && resultCode == RESULT_OK) {
            imageListUrls = data.getStringArrayListExtra("imagesList");

        }
        if (requestCode == REQUEST_CODE_REPAIRS && resultCode == RESULT_OK) {
            RepairsInfo RepairsInfo = (RepairsInfo) data.getSerializableExtra("repairs");
            task_repairs.setText(RepairsInfo.repairsName);
            repairsId = RepairsInfo.repairsId;
        }
        if (requestCode == REQUEST_CODE_REPAIRS_DEP && resultCode == RESULT_OK) {
            RepairsDepInfo repairsDepInfo = (RepairsDepInfo) data.getSerializableExtra("repairs_dep");
            task_repairs_dep.setText(repairsDepInfo.repairsDepName);
            repairsDepId = repairsDepInfo.repairsDepId;
        }

    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.resolved:
                strSolved = "true";
                break;
            case R.id.unsolved:

                strSolved = "false";
                break;
        }
    }


    @Override
    public void selectTaskType(String str) {

        task_type_name.setText(str);
        linear_hardware.setVisibility(str.equals("硬件") ? View.VISIBLE : View.GONE);
    }

    @Override
    public void changeArrowDirection() {

    }


    @Override
    public void selectTaskIssuer(IssueInfo issueInfo) {
        task_issuer.setText(issueInfo.issueName);
        issueId = issueInfo.issueId;
    }
}
